package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author tongchen
 * @create 2022-11-26 16:22
 */
public class TestRelect {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
        //1.获取类对象
        Class<?> clazz = Class.forName("reflect.Student");
        //获取类方法的全路径
        System.out.println(clazz.getName());
        //获取类的加载器
        System.out.println(clazz.getClassLoader());
        //获取包下的所有类
        System.out.println(clazz.getDeclaredClasses().getClass());
        //创建类的对象
        System.out.println("*********************");
        String name="ss";
        int age=10;
        Object o = clazz.newInstance();
        Student stu=(Student) o;
        stu.setAge(10);
        System.out.println("-----------------------------");
        System.out.println(clazz.getField("age"));
        System.out.println(clazz.getDeclaredField("name"));
        Field name1 = clazz.getDeclaredField("name");
        name1.setAccessible(true);
        name1.set(stu,"xiaomign");
//通过构造器创建对象
        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        Object xiaoming = declaredConstructor.newInstance("xiaoming", 19);
        System.out.println(xiaoming);
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for(int i=0;i<declaredConstructors.length;++i){
            System.out.println(declaredConstructors[i]);
        }


    }
}
